/**
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

/**
 * @file main.cpp
 */
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <fcntl.h>

#include "acl/acl.h"
#include "aclnn_channel_mixing.h"

#define SUCCESS 0
#define FAILED 1

#define INFO_LOG(fmt, args...) fprintf(stdout, "[INFO]  " fmt "\n", ##args)
#define WARN_LOG(fmt, args...) fprintf(stdout, "[WARN]  " fmt "\n", ##args)
#define ERROR_LOG(fmt, args...) fprintf(stderr, "[ERROR]  " fmt "\n", ##args)

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

bool ReadFile(const std::string &filePath, size_t fileSize, void *buffer, size_t bufferSize)
{
    struct stat sBuf;
    int fileStatus = stat(filePath.data(), &sBuf);
    if (fileStatus == -1) {
        ERROR_LOG("failed to get file %s", filePath.c_str());
        return false;
    }
    if (S_ISREG(sBuf.st_mode) == 0) {
        ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
        return false;
    }

    std::ifstream file;
    file.open(filePath, std::ios::binary);
    if (!file.is_open()) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    std::filebuf *buf = file.rdbuf();
    size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
    if (size == 0) {
        ERROR_LOG("file size is 0");
        file.close();
        return false;
    }
    if (size > bufferSize) {
        ERROR_LOG("file size is larger than buffer size");
        file.close();
        return false;
    }
    buf->pubseekpos(0, std::ios::in);
    buf->sgetn(static_cast<char *>(buffer), size);
    fileSize = size;
    file.close();
    return true;
}

bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
{
    if (buffer == nullptr) {
        ERROR_LOG("Write file failed. buffer is nullptr");
        return false;
    }

    int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
    if (fd < 0) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    auto writeSize = write(fd, buffer, size);
    (void) close(fd);
    if (writeSize != size) {
        ERROR_LOG("Write file Failed.");
        return false;
    }

    return true;
}

int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    // 固定写法，acl初始化
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return FAILED);

    return SUCCESS;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // 调用aclrtMalloc申请device侧内存
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclCreateTensor接口创建aclTensor
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(),
                              shape.size(), *deviceAddr);
    return SUCCESS;
}
#include <stdlib.h>
#include <cstring>
int main(int argc, char **argv)
{
    // 1. （固定写法）device/stream初始化, 参考acl对外接口列表
    // 根据自己的实际device填写deviceId
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return FAILED);

    int32_t B = 1;
    int32_t T = 1;

    {
        
        char *my_case = getenv("CHANNEL_MIXING_CASE");
        
        if (strcmp(my_case, "1") == 0) 
        {
            B = 1;
            T = 1;
        }
        else if (strcmp(my_case, "2") == 0) 
        {
            B = 1;
            T = 8;
        }
        else if (strcmp(my_case, "3") == 0) 
        {
            B = 1;
            T = 64;
        }
        else if (strcmp(my_case, "4") == 0) 
        {
            B = 1;
            T = 1024;
        }
        else if (strcmp(my_case, "5") == 0) 
        {
            B = 1;
            T = 8192;
        }
        else if (strcmp(my_case, "6") == 0) 
        {
            B = 7;
            T = 77;
        }
        else if (strcmp(my_case, "7") == 0) 
        {
            B = 8;
            T = 32;
        }
        else if (strcmp(my_case, "8") == 0) 
        {
            B = 9;
            T = 256;
        }
        else if (strcmp(my_case, "9") == 0) 
        {
            B = 5;
            T = 80;
        }
        else if (strcmp(my_case, "10") == 0) 
        {
            B = 6;
            T = 128;
        }
        else if (strcmp(my_case, "11") == 0) 
        {
            B = 1;
            T = 123;
        }
        else if (strcmp(my_case, "12") == 0) 
        {
            B = 100;
            T = 16;
        }
        else if (strcmp(my_case, "13") == 0) 
        {
            B = 200;
            T = 64;
        }
        else if (strcmp(my_case, "14") == 0) 
        {
            B = 11;
            T = 127;
        }
        else if (strcmp(my_case, "15") == 0) 
        {
            B = 3;
            T = 2048;
        }
        else if (strcmp(my_case, "0") == 0) 
        {
            B = 1;
            T = 80;
        }
    }

    
    int32_t C = 2560;

    // 2. 构造输入与输出，需要根据API的接口自定义构造
    std::vector<int64_t> inputXShape = {B, T, C};
    std::vector<int64_t> inputH0Shape = {B, 1, C};
    std::vector<int64_t> inputXkShape = {1, 1, C};
    std::vector<int64_t> inputKwShape = {4 * C, C};
    std::vector<int64_t> inputVwShape = {C, 4 * C};
    std::vector<int64_t> outputOutShape = {B, T, C};
    std::vector<int64_t> outputHtShape = {B, 1, C};
    std::vector<int64_t> outputHsShape = {T, 4 * C};
    void *inputXDeviceAddr = nullptr;
    void *inputH0DeviceAddr = nullptr;
    void *inputXkDeviceAddr = nullptr;
    void *inputKwDeviceAddr = nullptr;
    void *inputVwDeviceAddr = nullptr;
    void *outputOutDeviceAddr = nullptr;
    void *outputHtDeviceAddr = nullptr;
    void *outputHsDeviceAddr = nullptr;
    aclTensor *inputX = nullptr;
    aclTensor *inputH0 = nullptr;
    aclTensor *inputXk = nullptr;
    aclTensor *inputKw = nullptr;
    aclTensor *inputVw = nullptr;
    aclTensor *outputOut = nullptr;
    aclTensor *outputHt = nullptr;
    aclTensor *outputHs = nullptr;
    size_t inputXShapeSize = B * T * C;
    size_t inputH0ShapeSize = B * C;
    size_t inputXkShapeSize = C;
    size_t inputKwShapeSize = 4 * C * C;
    size_t inputVwShapeSize = C * 4 * C;
    size_t outputOutShapeSize = B * T * C;
    size_t outputHtShapeSize = B * C;
    size_t outputHsShapeSize = T * 4 * C;
    std::vector<aclFloat16> inputXHostData(inputXShapeSize);
    std::vector<aclFloat16> inputH0HostData(inputH0ShapeSize);
    std::vector<aclFloat16> inputXkHostData(inputXkShapeSize);
    std::vector<aclFloat16> inputKwHostData(inputKwShapeSize);
    std::vector<aclFloat16> inputVwHostData(inputVwShapeSize);
    std::vector<aclFloat16> outputOutHostData(outputOutShapeSize);
    std::vector<aclFloat16> outputHtHostData(outputHtShapeSize);
    std::vector<aclFloat16> outputHsHostData(outputHsShapeSize);
    size_t dataType = sizeof(uint16_t);
    size_t fileSize = 0;
    void ** input1=(void **)(&inputXHostData);
    void ** input2=(void **)(&inputH0HostData);
    void ** input3=(void **)(&inputXkHostData);
    void ** input4=(void **)(&inputKwHostData);
    void ** input5=(void **)(&inputVwHostData);
    //读取数据
    ReadFile("../input/input_x.bin", fileSize, *input1, inputXShapeSize * dataType);
    ReadFile("../input/input_h0.bin", fileSize, *input2, inputH0ShapeSize * dataType);
    ReadFile("../input/input_xk.bin", fileSize, *input3, inputXkShapeSize * dataType);
    ReadFile("../input/input_kw.bin", fileSize, *input4, inputKwShapeSize * dataType);
    ReadFile("../input/input_vw.bin", fileSize, *input5, inputVwShapeSize * dataType);

    INFO_LOG("Set input success");
    // 创建inputX aclTensor
    ret = CreateAclTensor(inputXHostData, inputXShape, &inputXDeviceAddr, aclDataType::ACL_FLOAT16, &inputX);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputH0HostData, inputH0Shape, &inputH0DeviceAddr, aclDataType::ACL_FLOAT16, &inputH0);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputXkHostData, inputXkShape, &inputXkDeviceAddr, aclDataType::ACL_FLOAT16, &inputXk);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputKwHostData, inputKwShape, &inputKwDeviceAddr, aclDataType::ACL_FLOAT16, &inputKw);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputVwHostData, inputVwShape, &inputVwDeviceAddr, aclDataType::ACL_FLOAT16, &inputVw);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    // 创建outputOut aclTensor
    ret = CreateAclTensor(outputOutHostData, outputOutShape, &outputOutDeviceAddr, aclDataType::ACL_FLOAT16, &outputOut);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(outputHtHostData, outputHtShape, &outputHtDeviceAddr, aclDataType::ACL_FLOAT16, &outputHt);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(outputHsHostData, outputHsShape, &outputHsDeviceAddr, aclDataType::ACL_FLOAT16, &outputHs);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);

    // 3. 调用CANN自定义算子库API
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;
    // 计算workspace大小并申请内存
    ret = aclnnChannelMixingGetWorkspaceSize(inputX, inputH0, inputXk, inputKw, inputVw, outputOut, outputHt, outputHs, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnChannelMixingGetWorkspaceSize failed. ERROR: %d\n", ret); return FAILED);
    void *workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return FAILED;);
    }
    // 执行算子
    ret = aclnnChannelMixing(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnChannelMixing failed. ERROR: %d\n", ret); return FAILED);

    // 4. （固定写法）同步等待任务执行结束
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return FAILED);

    // 5. 获取输出的值，将device侧内存上的结果拷贝至host侧，需要根据具体API的接口定义修改
    auto outsize = GetShapeSize(outputOutShape);
    std::vector<aclFloat16> resultData(outsize, 0);
    auto htsize = GetShapeSize(outputHtShape);
    std::vector<aclFloat16> resultHtData(htsize, 0);

    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outputOutDeviceAddr,
                      outsize * sizeof(aclFloat16), ACL_MEMCPY_DEVICE_TO_HOST);
    ret = aclrtMemcpy(resultHtData.data(), resultHtData.size() * sizeof(resultHtData[0]), outputHtDeviceAddr,
                      htsize * sizeof(aclFloat16), ACL_MEMCPY_DEVICE_TO_HOST);

    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return FAILED);
    void ** output1=(void **)(&resultData);
    void ** output2=(void **)(&resultHtData);
    //写出数据
    WriteFile("../output/output_out.bin", *output1, outputOutShapeSize * dataType);
    WriteFile("../output/output_ht.bin", *output2, outputHtShapeSize * dataType);
    INFO_LOG("Write output success");

    // 6. 释放aclTensor，需要根据具体API的接口定义修改
    aclDestroyTensor(inputX);
    aclDestroyTensor(inputH0);
    aclDestroyTensor(inputXk);
    aclDestroyTensor(inputKw);
    aclDestroyTensor(inputVw);
    aclDestroyTensor(outputOut);
    aclDestroyTensor(outputHt);
    aclDestroyTensor(outputHs);

    // 7. 释放device资源，需要根据具体API的接口定义修改
    aclrtFree(inputXDeviceAddr);
    aclrtFree(inputH0DeviceAddr);
    aclrtFree(inputXkDeviceAddr);
    aclrtFree(inputKwDeviceAddr);
    aclrtFree(inputVwDeviceAddr);
    aclrtFree(outputOutDeviceAddr);
    aclrtFree(outputHtDeviceAddr);
    aclrtFree(outputHsDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return SUCCESS;
}
